<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="品牌名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入品牌名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['procurementmanagement:brand:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['procurementmanagement:brand:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['procurementmanagement:brand:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="brandList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="品牌名称" align="center" prop="name" />
      <el-table-column label="品牌图标" align="center" prop="logo">
        <template slot-scope="scope">
          <el-image
            style="width: 50px; height: 50px"
            :src="scope.row.logo"
            :preview-src-list="[scope.row.logo]"
            fit="contain"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['procurementmanagement:brand:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['procurementmanagement:brand:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改品牌对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="品牌名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入品牌名称" />
        </el-form-item>
        <el-form-item label="品牌图标" prop="logo">
          <div v-if="form.logo" class="image-preview">
            <div class="image-item">
              <el-image
                style="width: 100px; height: 100px"
                :src="form.logo"
                fit="cover"
                :preview-src-list="[form.logo]"
              >
                <div slot="error" class="image-error">
                  <i class="el-icon-picture-outline"></i>
                </div>
              </el-image>
            </div>
          </div>

          <el-upload
            ref="upload"
            :on-remove="handleRemove"
            list-type="picture-card"
            :file-list="fileList"
            :on-change="handleFileChange"
            :auto-upload="false"
            action="#"
            :http-request="handleUploadRequest"
          >
            <i class="el-icon-plus"></i>
            <div slot="tip" class="el-upload__tip">请上传jpg, jpeg, png格式，建议分辨率不要超过800*800，大小不超过3M的1:1正方形图片</div>
          </el-upload>
          <el-button @click="submitUpload">上传</el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listBrand, getBrand, delBrand, addBrand, updateBrand } from "@/api/goods/brand";
import OSS from 'ali-oss';

export default {
  name: "Brand",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 品牌表格数据
      brandList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
      },
      // 表单参数
      form: {},
      // 文件列表
      fileList: [],
      // OSS客户端
      ossClient: null,
      // 表单校验
      rules: {
        name: [
          { required: true, message: '品牌名称不能为空', trigger: 'blur' }
        ],
        logo: [
          { required: true, message: '请上传品牌Logo', trigger: 'blur' }
        ]
      }
    };
  },
  created() {
    this.initOSSClient();
    this.getList();
  },
  methods: {
    // 初始化OSS客户端
    initOSSClient() {
      try {
        this.ossClient = new OSS({
          region: 'oss-cn-shenzhen',
          accessKeyId: 'LTAI5tS35yZTe5jnu1yJpniL',
          accessKeySecret: 'rKET9B5WNRxrGCMSsBJw8ugBqoaWKa',
          bucket: 'magicerp2',
          secure: true,
          endpoint: 'https://oss-cn-shenzhen.aliyuncs.com',
          cname: false
        });
      } catch (error) {
        console.error('OSS初始化失败:', error);
        this.$message.error('OSS服务初始化失败');
      }
    },

    // 文件状态改变时的钩子
    handleFileChange(file, fileList) {
      const uniqueFiles = fileList.reduce((acc, current) => {
        const x = acc.find(item => item.uid === current.uid);
        if (!x) {
          return acc.concat([current]);
        } else {
          return acc;
        }
      }, []);
      this.fileList = uniqueFiles;
    },

    // 提交上传
    submitUpload() {
      this.$refs.upload.submit();
    },

    // 自定义上传请求
    handleUploadRequest(options) {
      this.handleBeforeUpload(options.file);
    },

    // 上传前处理
    async handleBeforeUpload(file) {
      const validTypes = ['image/jpeg', 'image/png', 'image/jpg'];
      if (!validTypes.includes(file.type)) {
        this.$message.error('只能上传JPG/PNG格式的图片!');
        return false;
      }
      const isLt3M = file.size / 1024 / 1024 < 3;
      if (!isLt3M) {
        this.$message.error('图片大小不能超过3MB!');
        return false;
      }

      try {
        const fileName = `brand-logos/${Date.now()}-${file.name.replace(/\s+/g, '-')}`;
        const result = await this.ossClient.put(fileName, file, {
          headers: { 'Content-Type': file.type }
        });

        // 更新文件列表
        const newFileObject = {
          uid: file.uid,
          name: file.name,
          url: result.url,
          status: 'success'
        };

        const existingIndex = this.fileList.findIndex(f => f.uid === file.uid);
        if (existingIndex >= 0) {
          this.fileList.splice(existingIndex, 1, newFileObject);
        } else {
          this.fileList.push(newFileObject);
        }

        // 设置表单logo字段
        this.form.logo = result.url;

        this.$message.success('图片上传成功');
        return false;
      } catch (error) {
        console.error('上传失败:', error);
        this.$message.error(`上传失败: ${error.message}`);
        return false;
      }
    },

    // 删除图片
    async handleRemove(file, fileList) {
      try {
        await this.$confirm('确定删除这张图片吗?', '提示', {
          type: 'warning'
        });
        this.fileList = fileList;
        this.form.logo = '';
        if (file.response && file.response.data && file.response.data.url) {
          try {
            const urlObj = new URL(file.response.data.url);
            const fileName = decodeURIComponent(urlObj.pathname.substring(1));
            await this.ossClient.delete(fileName);
          } catch (ossError) {
            console.warn('OSS删除失败:', ossError);
          }
        }
        this.$message.success('删除成功');
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error);
        }
      }
    },

    /** 查询品牌列表 */
    getList() {
      this.loading = true;
      listBrand(this.queryParams).then(response => {
        this.brandList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    // 表单重置
    reset() {
      this.form = {
        brandId: null,
        name: null,
        logo: null,
        disabled: null
      };
      this.fileList = [];
      this.resetForm("form");
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.brandId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加品牌";
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const brandId = row.brandId || this.ids;
      getBrand(brandId).then(response => {
        this.form = response.data;
        if (this.form.logo) {
          this.fileList = [{
            name: '品牌Logo',
            url: this.form.logo
          }];
        }
        this.open = true;
        this.title = "修改品牌";
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.brandId != null) {
            updateBrand(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBrand(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const brandIds = row.brandId || this.ids;
      this.$modal.confirm('是否确认删除品牌编号为"' + brandIds + '"的数据项？').then(function() {
        return delBrand(brandIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    }
  }
};
</script>

<style scoped>
/* 图片预览样式 */
.image-preview {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 15px;
}

.image-item {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 5px;
}

.image-error {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
  color: #909399;
}

.el-upload__tip {
  font-size: 12px;
  color: #999;
}
</style>
